﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace Gui.Service
{
    class ApiClient
    {
        private readonly HttpClient client;
        private readonly string baseUrl;
        private static ApiClient instance;

        public static ApiClient Instance()
        {
            if (instance == null)
            {
                instance = new ApiClient();
            }
            return instance;
        }

        private ApiClient()
        {
            baseUrl = System.Configuration.ConfigurationManager.AppSettings["ServiceUrl"];
            if (string.IsNullOrEmpty(baseUrl))
            {
                baseUrl = "http://10.0.0.44:8080/api";
            }
            client = new HttpClient();
        }

        public async Task<T> PostJson<T>(string reletiveUrl, object obj) where T : MyHttpResult, new()
        {
            string uri = baseUrl + reletiveUrl;
            HttpResponseMessage response;
            var body = new StringContent(JsonConvert.SerializeObject(obj), Encoding.UTF8, "application/json");
            try
            {
                response = await client.PostAsync(uri, body);
            }
            catch(HttpRequestException e)
            {
                return makeErrResult<T>("网络请求异常：" + e.InnerException.Message);
            }
            return await handleResponse<T>(response);
        }


        public async Task<T> PostForm<T>(string reletiveUrl, List<KeyValuePair<string, string>> postParams) where T : MyHttpResult, new()
        {
            string uri = baseUrl + reletiveUrl;
            FormUrlEncodedContent content = new FormUrlEncodedContent(postParams);
            HttpResponseMessage response;

            try
            {
                response = await client.PostAsync(uri, content);
            }
            catch (HttpRequestException e)
            {
                return makeErrResult<T>("网络请求异常：" + e.InnerException.Message);
            }

            return await handleResponse<T>(response);
        }

        public async Task<T> Get<T>(string reletiveUrl) where T : MyHttpResult, new()
        {
            string uri = baseUrl + reletiveUrl;
            HttpResponseMessage response;
            try
            {
                response = await client.GetAsync(uri);
            }
            catch (HttpRequestException e)
            {
                return makeErrResult<T>("网络请求异常：" + e.InnerException.Message);
            }

            return await handleResponse<T>(response);
        }

        private async Task<T> handleResponse<T>(HttpResponseMessage response) where T : MyHttpResult, new()
        {
            T backResult;
            if (response.StatusCode != HttpStatusCode.OK)
            {
                return makeErrResult<T>("网络请求异常,状态码：" + (int)response.StatusCode);
            }

            string result = await response.Content.ReadAsStringAsync();
            try
            {
                backResult = JsonConvert.DeserializeObject<T>(result);
            }
            catch (Exception)
            {
                return makeErrResult<T>("json反序列化失败");
            }

            return backResult;
        }

        T makeErrResult<T>(string errmsg) where T : MyHttpResult, new()
        {
            return new T() { errMsg = errmsg };
        }
    }
}
